Skip to main content

HTML/HTML5 Complete Interview Guide

Table of Contentsโ€‹


Introductionโ€‹

HTML (HyperText Markup Language) is the standard markup language for creating web pages. HTML5 is the fifth and current major version of HTML, introducing numerous new features, semantic elements, and APIs that have transformed web development.

This guide covers everything you need to know about HTML/HTML5 from an interview perspective, including fundamental concepts, new features, best practices, and common interview questions.

HTML Fundamentalsโ€‹

What is HTML?โ€‹

HTML is a markup language that defines the structure and content of web pages. It uses a system of tags to describe different types of content and their relationships. Browsers parse HTML to render web pages.

Key characteristics:

  • Markup language, not a programming language
  • Uses tags enclosed in angle brackets (<tag>)
  • Case-insensitive (but lowercase is convention)
  • Consists of elements, attributes, and content
  • Forms the structural layer of web pages

HTML Document Structureโ€‹

Every HTML document follows a basic structure:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page Title</title>
</head>
<body>
<!-- Content goes here -->
</body>
</html>

Components:

  • <!DOCTYPE html>: Declares document type and HTML version
  • <html>: Root element containing all content
  • <head>: Contains metadata, links to resources, and scripts
  • <body>: Contains visible page content

DOCTYPE Declarationโ€‹

The DOCTYPE declaration tells the browser which version of HTML the page uses and triggers standards mode rendering.

HTML5 DOCTYPE:

<!DOCTYPE html>

Why it matters:

  • Ensures consistent rendering across browsers
  • Triggers standards mode vs quirks mode
  • HTML5 simplified from previous verbose declarations
  • Must be the very first thing in an HTML document

Previous DOCTYPE examples:

<!-- HTML 4.01 Strict -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<!-- XHTML 1.0 Strict -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

HTML Elements and Tagsโ€‹

Elements: Complete HTML structures including opening tag, content, and closing tag Tags: Markers that define element boundaries

Types of elements:

Paired tags:

<p>This is a paragraph</p>
<div>This is a division</div>

Self-closing/Void tags:

<img src="image.jpg" alt="Description">
<br>
<hr>
<input type="text">
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">

Block-level elements:

  • Take up full width available
  • Start on new line
  • Examples: <div>, <p>, <h1>-<h6>, <section>, <article>

Inline elements:

  • Take up only necessary width
  • Don't start new line
  • Examples: <span>, <a>, <strong>, <em>, <img>

Attributesโ€‹

Attributes provide additional information about elements and modify their behavior or appearance.

Syntax:

<element attribute="value">Content</element>

Common global attributes:

  • id: Unique identifier for element
  • class: One or more class names for styling/scripting
  • style: Inline CSS styles
  • title: Advisory information (tooltip)
  • data-*: Custom data attributes
  • hidden: Hides element from display
  • tabindex: Controls keyboard navigation order
  • contenteditable: Makes element editable
  • draggable: Makes element draggable

Boolean attributes:

<input type="checkbox" checked>
<button disabled>Click me</button>
<script async src="script.js"></script>

HTML5 New Featuresโ€‹

Key Improvementsโ€‹

HTML5 introduced significant improvements over HTML4:

  1. Simplified syntax - Cleaner DOCTYPE, character set declaration
  2. New semantic elements - Better document structure
  3. Multimedia support - Native audio and video
  4. Graphics capabilities - Canvas and SVG
  5. Enhanced forms - New input types and validation
  6. Web APIs - Geolocation, Web Storage, Web Workers
  7. Improved parsing - Better error handling
  8. Offline capabilities - Application cache, service workers
  9. Mobile-friendly - Better support for mobile devices

New Semantic Elementsโ€‹

HTML5 introduced semantic elements that clearly describe their meaning:

<header>      <!-- Header content -->
<nav> <!-- Navigation links -->
<main> <!-- Main content -->
<article> <!-- Independent, self-contained content -->
<section> <!-- Thematic grouping of content -->
<aside> <!-- Content aside from main content -->
<footer> <!-- Footer content -->
<figure> <!-- Self-contained content like images -->
<figcaption> <!-- Caption for figure -->
<mark> <!-- Highlighted/marked text -->
<time> <!-- Date/time -->
<details> <!-- Additional details user can show/hide -->
<summary> <!-- Heading for details element -->

Example structure:

<header>
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
</ul>
</nav>
</header>

<main>
<article>
<header>
<h1>Article Title</h1>
<time datetime="2024-01-15">January 15, 2024</time>
</header>
<section>
<h2>Section Heading</h2>
<p>Content here...</p>
</section>
</article>

<aside>
<h3>Related Links</h3>
</aside>
</main>

<footer>
<p>&copy; 2024 Company Name</p>
</footer>

New Form Elementsโ€‹

Datalist: Provides autocomplete suggestions for input fields.

<input list="browsers" name="browser">
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
<option value="Safari">
<option value="Edge">
</datalist>

Output: Displays calculation results.

<form oninput="result.value=parseInt(a.value)+parseInt(b.value)">
<input type="range" id="a" value="50"> +
<input type="number" id="b" value="50"> =
<output name="result" for="a b">100</output>
</form>

Progress: Shows task completion progress.

<progress value="70" max="100">70%</progress>

Meter: Shows scalar measurement within a range.

<meter value="6" min="0" max="10" low="3" high="7" optimum="5">6 out of 10</meter>

New Input Typesโ€‹

HTML5 introduced many new input types with built-in validation:

<!-- Email with validation -->
<input type="email" required>

<!-- URL with validation -->
<input type="url" placeholder="https://example.com">

<!-- Number with min/max -->
<input type="number" min="1" max="100" step="1">

<!-- Range slider -->
<input type="range" min="0" max="100" value="50">

<!-- Date picker -->
<input type="date">

<!-- Time picker -->
<input type="time">

<!-- Date and time -->
<input type="datetime-local">

<!-- Month picker -->
<input type="month">

<!-- Week picker -->
<input type="week">

<!-- Color picker -->
<input type="color" value="#ff0000">

<!-- Telephone -->
<input type="tel" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}">

<!-- Search box -->
<input type="search" placeholder="Search...">

New APIsโ€‹

HTML5 introduced powerful JavaScript APIs:

Geolocation API:

navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position.coords.latitude);
console.log(position.coords.longitude);
}
);

Drag and Drop API:

<div draggable="true" ondragstart="drag(event)">Drag me</div>
<div ondrop="drop(event)" ondragover="allowDrop(event)">Drop here</div>

Web Workers: Run scripts in background threads without blocking UI.

WebSocket API: Full-duplex communication channels over single TCP connection.

Canvas API: Draw graphics programmatically using JavaScript.

History API: Manipulate browser history for single-page applications.

Semantic HTMLโ€‹

Why Semantics Matterโ€‹

Using semantic HTML provides multiple benefits:

  1. Accessibility - Screen readers understand content structure
  2. SEO - Search engines better understand content importance
  3. Maintainability - Code is more readable and self-documenting
  4. Consistency - Standard elements ensure consistent behavior
  5. Future-proofing - Semantic markup adapts better to new devices

Semantic vs Non-Semantic Elementsโ€‹

Semantic elements:

<header>, <nav>, <main>, <article>, <section>, <aside>, <footer>
<h1>-<h6>, <p>, <figure>, <figcaption>, <mark>, <time>

Non-semantic elements:

<div>, <span>

Bad practice (non-semantic):

<div class="header">
<div class="nav">
<div class="nav-item">Home</div>
</div>
</div>
<div class="content">
<div class="article">
<div class="title">Article Title</div>
<div class="body">Content...</div>
</div>
</div>

Good practice (semantic):

<header>
<nav>
<a href="#home">Home</a>
</nav>
</header>
<main>
<article>
<h1>Article Title</h1>
<p>Content...</p>
</article>
</main>

Document Outlineโ€‹

HTML5 introduced the concept of document outline where each sectioning element (<article>, <section>, <nav>, <aside>) creates a new section in the outline.

Proper heading hierarchy:

<h1>Main Title</h1>
<section>
<h2>Section Title</h2>
<h3>Subsection Title</h3>
</section>
<section>
<h2>Another Section</h2>
</section>

Common mistake - skipping levels:

<!-- Bad: Skipping from h1 to h3 -->
<h1>Title</h1>
<h3>Subtitle</h3>

<!-- Good: Sequential hierarchy -->
<h1>Title</h1>
<h2>Subtitle</h2>

Forms and Inputโ€‹

Form Elementsโ€‹

Basic form structure:

<form action="/submit" method="POST" enctype="multipart/form-data">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>

<label for="email">Email:</label>
<input type="email" id="email" name="email" required>

<label for="password">Password:</label>
<input type="password" id="password" name="password" required>

<label for="country">Country:</label>
<select id="country" name="country">
<option value="">Select...</option>
<option value="us">United States</option>
<option value="uk">United Kingdom</option>
</select>

<label for="bio">Bio:</label>
<textarea id="bio" name="bio" rows="4"></textarea>

<fieldset>
<legend>Preferences</legend>
<label>
<input type="checkbox" name="newsletter" value="yes">
Subscribe to newsletter
</label>
</fieldset>

<button type="submit">Submit</button>
</form>

Form attributes:

  • action: URL where form data is sent
  • method: HTTP method (GET or POST)
  • enctype: How form data is encoded
    • application/x-www-form-urlencoded (default)
    • multipart/form-data (for file uploads)
    • text/plain
  • autocomplete: Enable/disable autocomplete
  • novalidate: Disable HTML5 validation
  • target: Where to display response (_blank, _self, _parent, _top)

Form Validationโ€‹

HTML5 built-in validation attributes:

<!-- Required field -->
<input type="text" required>

<!-- Pattern matching -->
<input type="text" pattern="[A-Za-z]{3,}" title="At least 3 letters">

<!-- Min/Max length -->
<input type="text" minlength="3" maxlength="20">

<!-- Min/Max value -->
<input type="number" min="1" max="100">

<!-- Multiple values (email) -->
<input type="email" multiple>

<!-- Custom validation message -->
<input type="email" required
oninvalid="this.setCustomValidity('Please enter valid email')"
oninput="this.setCustomValidity('')">

Validation pseudo-classes:

input:valid {
border-color: green;
}

input:invalid {
border-color: red;
}

input:required {
border-left: 3px solid blue;
}

input:optional {
border-left: 3px solid gray;
}

JavaScript validation API:

const input = document.querySelector('input');

// Check validity
if (input.checkValidity()) {
console.log('Valid');
} else {
console.log(input.validationMessage);
}

// Custom validation
input.setCustomValidity('This field must contain X');

// Clear custom validation
input.setCustomValidity('');

Form Attributesโ€‹

Input attributes:

<!-- Autofocus on page load -->
<input type="text" autofocus>

<!-- Placeholder text -->
<input type="text" placeholder="Enter name...">

<!-- Readonly (can be focused, submitted) -->
<input type="text" value="Cannot edit" readonly>

<!-- Disabled (cannot be focused, not submitted) -->
<input type="text" disabled>

<!-- Autocomplete -->
<input type="email" autocomplete="email">

<!-- Input mode for virtual keyboards -->
<input type="text" inputmode="numeric">

<!-- List for autocomplete -->
<input type="text" list="suggestions">

<!-- Multiple file upload -->
<input type="file" multiple accept="image/*">

Multimedia Elementsโ€‹

Audio and Videoโ€‹

Video element:

<video width="640" height="360" controls poster="thumbnail.jpg">
<source src="video.mp4" type="video/mp4">
<source src="video.webm" type="video/webm">
<track src="subtitles_en.vtt" kind="subtitles" srclang="en" label="English">
Your browser doesn't support video.
</video>

Video attributes:

  • controls: Show playback controls
  • autoplay: Start playing automatically
  • loop: Loop playback
  • muted: Mute audio by default
  • preload: How to preload (none, metadata, auto)
  • poster: Image shown before playback

Audio element:

<audio controls>
<source src="audio.mp3" type="audio/mpeg">
<source src="audio.ogg" type="audio/ogg">
Your browser doesn't support audio.
</audio>

JavaScript media API:

const video = document.querySelector('video');

video.play();
video.pause();
video.currentTime = 10; // Skip to 10 seconds
video.volume = 0.5; // 50% volume
video.playbackRate = 1.5; // 1.5x speed

// Event listeners
video.addEventListener('play', () => console.log('Playing'));
video.addEventListener('ended', () => console.log('Finished'));

Canvasโ€‹

Canvas allows drawing graphics via JavaScript:

<canvas id="myCanvas" width="500" height="400"></canvas>

<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

// Draw rectangle
ctx.fillStyle = 'blue';
ctx.fillRect(50, 50, 150, 100);

// Draw circle
ctx.beginPath();
ctx.arc(300, 100, 50, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill();

// Draw text
ctx.font = '30px Arial';
ctx.fillStyle = 'black';
ctx.fillText('Hello Canvas', 100, 250);

// Draw line
ctx.beginPath();
ctx.moveTo(50, 300);
ctx.lineTo(450, 350);
ctx.strokeStyle = 'green';
ctx.lineWidth = 5;
ctx.stroke();
</script>

SVGโ€‹

SVG (Scalable Vector Graphics) can be embedded directly in HTML5:

<svg width="200" height="200">
<circle cx="100" cy="100" r="80" fill="blue" />
<rect x="50" y="50" width="100" height="100" fill="red" opacity="0.5" />
<line x1="0" y1="0" x2="200" y2="200" stroke="green" stroke-width="2" />
<text x="100" y="100" text-anchor="middle" fill="white">SVG Text</text>
</svg>

Canvas vs SVG:

  • Canvas: Raster-based, pixel manipulation, better for many objects, games
  • SVG: Vector-based, scalable, DOM-based, better for interactive graphics

HTML5 Storageโ€‹

localStorage vs sessionStorageโ€‹

Both provide client-side storage with simple key-value API:

localStorage:

  • Persists until explicitly cleared
  • Shared across all tabs/windows of same origin
  • Typical limit: 5-10MB

sessionStorage:

  • Persists only for page session
  • Separate for each tab/window
  • Cleared when tab/window closes

API (identical for both):

// Store data
localStorage.setItem('username', 'john');
localStorage.setItem('user', JSON.stringify({name: 'John', age: 30}));

// Retrieve data
const username = localStorage.getItem('username');
const user = JSON.parse(localStorage.getItem('user'));

// Remove item
localStorage.removeItem('username');

// Clear all
localStorage.clear();

// Get number of items
console.log(localStorage.length);

// Get key by index
const key = localStorage.key(0);

// Using property access (not recommended)
localStorage.username = 'john';
console.log(localStorage.username);

Storage event:

// Listen for storage changes (in other tabs)
window.addEventListener('storage', (e) => {
console.log('Key:', e.key);
console.log('Old value:', e.oldValue);
console.log('New value:', e.newValue);
console.log('URL:', e.url);
});

Cookies vs Web Storageโ€‹

Cookies:

  • Sent with every HTTP request (increases overhead)
  • 4KB limit per cookie
  • Can set expiration date
  • Can be HTTP-only (not accessible via JavaScript)
  • Can be Secure (HTTPS only)

Web Storage:

  • Not sent with requests
  • 5-10MB storage limit
  • Only accessible via JavaScript
  • Simpler API
  • No expiration (localStorage) or session-based (sessionStorage)

When to use cookies:

  • Server needs the data
  • Need expiration control
  • Need secure/HTTP-only flags

When to use Web Storage:

  • Client-side only data
  • Larger storage needs
  • Better performance (no network overhead)

IndexedDBโ€‹

IndexedDB is a low-level API for storing significant amounts of structured data:

// Open database
const request = indexedDB.open('MyDatabase', 1);

request.onupgradeneeded = (event) => {
const db = event.target.result;

// Create object store
const objectStore = db.createObjectStore('users', { keyPath: 'id', autoIncrement: true });

// Create indexes
objectStore.createIndex('email', 'email', { unique: true });
objectStore.createIndex('name', 'name', { unique: false });
};

request.onsuccess = (event) => {
const db = event.target.result;

// Add data
const transaction = db.transaction(['users'], 'readwrite');
const objectStore = transaction.objectStore('users');
objectStore.add({ name: 'John', email: 'john@example.com' });

// Read data
const getRequest = objectStore.get(1);
getRequest.onsuccess = () => {
console.log(getRequest.result);
};
};

Meta Tags and SEOโ€‹

Essential Meta Tagsโ€‹

<head>
<!-- Character encoding -->
<meta charset="UTF-8">

<!-- Viewport for responsive design -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<!-- Page description for search engines -->
<meta name="description" content="Brief page description (150-160 chars)">

<!-- Keywords (less important now) -->
<meta name="keywords" content="keyword1, keyword2, keyword3">

<!-- Author -->
<meta name="author" content="Author Name">

<!-- Robots directives -->
<meta name="robots" content="index, follow">

<!-- Canonical URL -->
<link rel="canonical" href="https://example.com/page">

<!-- Language -->
<html lang="en">

<!-- Theme color for mobile browsers -->
<meta name="theme-color" content="#4285f4">

<!-- Favicon -->
<link rel="icon" type="image/png" href="/favicon.png">

<!-- Apple touch icon -->
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
</head>

Open Graph and Twitter Cardsโ€‹

Open Graph (Facebook, LinkedIn):

<meta property="og:title" content="Page Title">
<meta property="og:description" content="Page description">
<meta property="og:image" content="https://example.com/image.jpg">
<meta property="og:url" content="https://example.com/page">
<meta property="og:type" content="website">
<meta property="og:site_name" content="Site Name">

Twitter Cards:

<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@username">
<meta name="twitter:title" content="Page Title">
<meta name="twitter:description" content="Page description">
<meta name="twitter:image" content="https://example.com/image.jpg">

Accessibilityโ€‹

ARIA Attributesโ€‹

ARIA (Accessible Rich Internet Applications) provides additional semantics for assistive technologies:

ARIA roles:

<div role="navigation">Navigation content</div>
<div role="main">Main content</div>
<div role="complementary">Sidebar content</div>
<button role="button" aria-pressed="false">Toggle</button>
<div role="alert">Important message</div>

ARIA states and properties:

<!-- Labeling -->
<button aria-label="Close dialog">X</button>
<div aria-labelledby="section-heading">
<h2 id="section-heading">Section Title</h2>
</div>

<!-- Descriptions -->
<input type="text" aria-describedby="name-help">
<span id="name-help">Enter your full name</span>

<!-- States -->
<button aria-pressed="true">Active</button>
<div aria-expanded="false">Collapsed content</div>
<input type="checkbox" aria-checked="true">
<button aria-disabled="true">Disabled</button>

<!-- Live regions -->
<div aria-live="polite">Updates announced politely</div>
<div aria-live="assertive">Urgent updates</div>

<!-- Hidden content -->
<div aria-hidden="true">Hidden from screen readers</div>

Accessibility Best Practicesโ€‹

Semantic HTML: Use appropriate elements instead of generic divs/spans with ARIA.

Keyboard navigation:

<!-- All interactive elements should be keyboard accessible -->
<button tabindex="0">Clickable</button>
<div tabindex="-1">Programmatically focusable</div>

Alt text for images:

<!-- Descriptive alt text -->
<img src="chart.png" alt="Sales increased 25% in Q4">

<!-- Decorative images -->
<img src="decorative.png" alt="">

Form labels:

<!-- Always associate labels with inputs -->
<label for="email">Email:</label>
<input type="email" id="email" name="email">

<!-- Or wrap input -->
<label>
Email:
<input type="email" name="email">
</label>

Focus indicators:

/* Never remove focus outlines without replacement */
button:focus {
outline: 2px solid blue;
outline-offset: 2px;
}

Color contrast: Ensure sufficient contrast ratio (WCAG guidelines):

  • Normal text: 4.5:1 minimum
  • Large text: 3:1 minimum

Skip links:

<a href="#main-content" class="skip-link">Skip to main content</a>
<main id="main-content">
<!-- Content -->
</main>

HTML Best Practicesโ€‹

  1. Use semantic elements - Choose appropriate HTML5 semantic tags
  2. Valid HTML - Write valid, well-formed HTML
  3. Proper nesting - Close tags in correct order
  4. Lowercase tags and attributes - Use lowercase for consistency
  5. Quote attribute values - Always quote attribute values
  6. Include alt text - All images should have meaningful alt attributes
  7. Use relative URLs - When possible, for easier maintenance
  8. Separate concerns - Keep HTML, CSS, and JavaScript separate
  9. Minimize inline styles - Use external stylesheets
  10. Accessibility first - Consider accessibility from the start
  11. Mobile-first - Design for mobile, enhance for desktop
  12. Validate markup - Use W3C validator to check HTML
  13. Use comments wisely - Comment complex structures, not obvious code
  14. Consistent indentation - Use 2 or 4 spaces consistently
  15. One h1 per page - Use single main heading for SEO

Performance Optimizationโ€‹

Minimize DOM size:

  • Keep DOM depth under 32 levels
  • Avoid more than 60 children per parent
  • Limit total DOM nodes to under 1500

Optimize images:

<!-- Responsive images -->
<img srcset="small.jpg 480w, medium.jpg 800w, large.jpg 1200w"
sizes="(max-width: 600px) 480px, 800px"
src="medium.jpg" alt="Description">

<!-- Lazy loading -->
<img src="image.jpg" loading="lazy" alt="Description">

<!-- Modern formats with fallback -->
<picture>
<source srcset="image.webp" type="image/webp">
<source srcset="image.jpg" type="image/jpeg">
<img src="image.jpg" alt="Description">
</picture>

Preload critical resources:

<link rel="preload" href="critical.css" as="style">
<link rel="preload" href="font.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preconnect" href="https://cdn.example.com">
<link rel="dns-prefetch" href="https://analytics.example.com">

Defer non-critical resources:

<script src="script.js" defer></script>
<script src="analytics.js" async></script>

Minimize HTTP requests:

  • Combine files where appropriate
  • Use CSS sprites for small images
  • Inline critical CSS
  • Remove unused code

Common Interview Questionsโ€‹

Q1: What's the difference between HTML and HTML5?โ€‹

HTML5 is the latest version with new features:

  • New semantic elements (header, nav, article, section, footer)
  • Audio and video support without plugins
  • Canvas and SVG for graphics
  • New form input types and validation
  • Web Storage (localStorage, sessionStorage)
  • New APIs (Geolocation, Web Workers, WebSocket)
  • Improved accessibility and SEO
  • Better mobile support

Q2: What's the difference between <div> and <span>?โ€‹

  • <div> is block-level: takes full width, starts on new line
  • <span> is inline: takes only necessary width, doesn't break line
  • Both are non-semantic containers
  • Use semantic alternatives when possible

Q3: What's the difference between id and class?โ€‹

  • id: Unique identifier, one per page, higher CSS specificity
  • class: Reusable identifier, multiple per element, lower specificity
  • id can be used for fragment identifiers in URLs (#section)
  • class better for styling multiple elements

Q4: What are data attributes?โ€‹

Custom attributes starting with data- for storing custom data:

<div data-user-id="123" data-role="admin">User Info</div>
const element = document.querySelector('div');
console.log(element.dataset.userId); // "123"
console.log(element.dataset.role); // "admin"
element.dataset.status = 'active'; // Sets data-status="active"

Q5: Explain semantic HTML and its benefitsโ€‹

Semantic HTML uses elements that clearly describe their meaning:

  • Better accessibility for screen readers
  • Improved SEO as search engines understand content
  • More maintainable code
  • Consistent behavior across browsers
  • Examples: <header>, <nav>, <article>, <aside>, <footer>

Q6: What's the difference between localStorage and sessionStorage?โ€‹

  • localStorage: Persists until explicitly deleted, shared across tabs
  • sessionStorage: Cleared when tab closes, isolated per tab
  • Both have same API and 5-10MB storage limit
  • Both store string data only (use JSON for objects)

Q7: What's the purpose of DOCTYPE?โ€‹

DOCTYPE tells the browser which HTML version to use and triggers standards mode:

  • <!DOCTYPE html> for HTML5
  • Prevents quirks mode rendering
  • Must be first line in document
  • HTML5 simplified from previous verbose declarations

Q8: Explain the difference between <script>, <script async>, and <script defer>โ€‹

  • Normal: Blocks HTML parsing, executes immediately
  • async: Downloads in parallel, executes as soon as ready (order not guaranteed)
  • defer: Downloads in parallel, executes after HTML parsing (order maintained)
<script src="blocking.js"></script>
<script src="independent.js" async></script>
<script src="needs-dom.js" defer></script>

Q9: What are void/self-closing elements?โ€‹

Elements that don't have closing tags or content:

<img src="image.jpg" alt="Description">
<br>
<hr>
<input type="text">
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
<area>
<base>
<col>
<embed>
<source>
<track>
<wbr>

Q10: What's the difference between <strong> and <b>, <em> and <i>?โ€‹

  • <strong>: Semantic importance, screen readers emphasize
  • <b>: Visual bold, no semantic meaning
  • <em>: Semantic emphasis, screen readers emphasize
  • <i>: Visual italic, no semantic meaning

Always prefer semantic tags for accessibility.

Q11: How do you optimize web page loading?โ€‹

  • Minimize HTTP requests
  • Compress images and use modern formats (WebP, AVIF)
  • Lazy load below-the-fold content
  • Use CDN for static resources
  • Minify HTML, CSS, JavaScript
  • Enable gzip/Brotli compression
  • Use browser caching
  • Preload critical resources
  • Defer non-critical JavaScript
  • Reduce DOM size and complexity

Q12: What's the difference between cookies and Web Storage?โ€‹

Cookies:

  • 4KB limit per cookie
  • Sent with every HTTP request
  • Can set expiration date
  • Accessible to server and client
  • Can be HTTP-only and Secure

Web Storage:

  • 5-10MB limit
  • Not sent with requests
  • localStorage persists, sessionStorage is session-based
  • Client-side only
  • Simpler API

Q13: What are Web Workers?โ€‹

JavaScript running in background threads without blocking the UI:

// main.js
const worker = new Worker('worker.js');
worker.postMessage({ data: 'process this' });
worker.onmessage = (e) => console.log(e.data);

// worker.js
self.onmessage = (e) => {
// Heavy computation
const result = process(e.data);
self.postMessage(result);
};

Use cases: Heavy calculations, data processing, background tasks

Q14: Explain the <canvas> elementโ€‹

Canvas allows drawing graphics via JavaScript:

  • Raster-based (pixel manipulation)
  • Bitmap graphics drawn with JavaScript
  • Good for games, animations, visualizations
  • No DOM for drawn elements
  • Better performance with many objects
<canvas id="canvas" width="500" height="400"></canvas>

Q15: What are meta tags used for?โ€‹

Meta tags provide metadata about the HTML document:

  • Character encoding: <meta charset="UTF-8">
  • Viewport for responsive design: <meta name="viewport"...>
  • SEO description: <meta name="description"...>
  • Social media cards: Open Graph, Twitter Cards
  • Browser behavior: theme-color, robots
  • Not visible on page but used by browsers and search engines

Q16: What's the difference between GET and POST?โ€‹

GET:

  • Data in URL query string
  • Visible in browser history
  • Can be bookmarked
  • Limited data length (URL length limit)
  • Idempotent (safe to repeat)
  • Used for retrieving data

POST:

  • Data in request body
  • Not visible in URL
  • Cannot be bookmarked
  • No size limitation
  • Not idempotent
  • Used for submitting data

Q17: What is progressive enhancement?โ€‹

Development approach that starts with basic functionality that works everywhere, then adds enhancements for capable browsers:

<!-- Basic link works everywhere -->
<a href="/page" class="modal-trigger">Open</a>

<!-- JavaScript adds modal behavior where supported -->
<script>
if ('querySelector' in document) {
// Add modal functionality
}
</script>

Q18: What are ARIA roles and when would you use them?โ€‹

ARIA (Accessible Rich Internet Applications) provides additional semantics for assistive technologies:

<div role="navigation">
<div role="button" tabindex="0" aria-pressed="false">
<div role="alert" aria-live="assertive">

Use ARIA when:

  • Native HTML elements don't fit the pattern
  • Building custom widgets
  • Dynamic content changes need announcement
  • However, prefer semantic HTML over ARIA when possible

Q19: Explain HTML5 form validationโ€‹

HTML5 provides built-in validation without JavaScript:

<input type="email" required>
<input type="number" min="1" max="100">
<input type="text" pattern="[A-Za-z]{3,}" title="At least 3 letters">
<input type="text" minlength="3" maxlength="20">

Validation pseudo-classes: :valid, :invalid, :required, :optional

Can be controlled via JavaScript:

input.checkValidity(); // Returns boolean
input.setCustomValidity('Error message');

Q20: What's the difference between <article> and <section>?โ€‹

  • <article>: Self-contained, independently distributable content (blog post, news article, comment)
  • <section>: Thematic grouping of content, typically with a heading

An article can contain sections, and sections can contain articles.

<article>
<h1>Blog Post Title</h1>
<section>
<h2>Introduction</h2>
<p>Content...</p>
</section>
<section>
<h2>Main Content</h2>
<p>Content...</p>
</section>
</article>

Coding Challengesโ€‹

Challenge 1: Create an accessible formโ€‹

<form action="/submit" method="POST" novalidate>
<fieldset>
<legend>User Registration</legend>

<div class="form-group">
<label for="username">Username *</label>
<input
type="text"
id="username"
name="username"
required
minlength="3"
aria-describedby="username-help"
>
<span id="username-help" class="help-text">
At least 3 characters
</span>
</div>

<div class="form-group">
<label for="email">Email *</label>
<input
type="email"
id="email"
name="email"
required
aria-describedby="email-help"
>
<span id="email-help" class="help-text">
We'll never share your email
</span>
</div>

<div class="form-group">
<label for="password">Password *</label>
<input
type="password"
id="password"
name="password"
required
minlength="8"
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
aria-describedby="password-help"
>
<span id="password-help" class="help-text">
Must contain uppercase, lowercase, and number
</span>
</div>

<div class="form-group">
<label for="country">Country</label>
<select id="country" name="country">
<option value="">Select country</option>
<option value="us">United States</option>
<option value="uk">United Kingdom</option>
<option value="ca">Canada</option>
</select>
</div>

<div class="form-group">
<fieldset>
<legend>Interests</legend>
<label>
<input type="checkbox" name="interests" value="tech">
Technology
</label>
<label>
<input type="checkbox" name="interests" value="sports">
Sports
</label>
</fieldset>
</div>

<button type="submit">Register</button>
</fieldset>
</form>

Challenge 2: Create a semantic blog post layoutโ€‹

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Understanding semantic HTML in modern web development">
<title>Semantic HTML Guide | My Blog</title>
</head>
<body>
<header>
<nav aria-label="Main navigation">
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
<li><a href="/blog" aria-current="page">Blog</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
</header>

<main>
<article>
<header>
<h1>Understanding Semantic HTML</h1>
<p>
<time datetime="2024-01-15">January 15, 2024</time>
by <span>John Doe</span>
</p>
<p class="summary">
Learn why semantic HTML matters for accessibility and SEO
</p>
</header>

<figure>
<img
src="semantic-html.jpg"
alt="Diagram showing HTML5 semantic elements structure"
loading="lazy"
>
<figcaption>HTML5 semantic structure example</figcaption>
</figure>

<section>
<h2>Introduction</h2>
<p>
Semantic HTML uses elements that clearly describe
their meaning to both the browser and developer...
</p>
</section>

<section>
<h2>Key Benefits</h2>
<ul>
<li>Improved accessibility</li>
<li>Better SEO</li>
<li>Easier maintenance</li>
</ul>
</section>

<section>
<h2>Common Semantic Elements</h2>
<p>Let's explore the most important semantic elements...</p>
</section>

<footer>
<p>Tags:
<a href="/tags/html" rel="tag">HTML</a>,
<a href="/tags/webdev" rel="tag">Web Development</a>
</p>
</footer>
</article>

<aside aria-labelledby="related-heading">
<h2 id="related-heading">Related Articles</h2>
<nav aria-label="Related articles">
<ul>
<li><a href="/css-basics">CSS Basics</a></li>
<li><a href="/javascript-intro">JavaScript Introduction</a></li>
</ul>
</nav>
</aside>
</main>

<footer>
<p>&copy; 2024 My Blog. All rights reserved.</p>
<nav aria-label="Footer navigation">
<ul>
<li><a href="/privacy">Privacy Policy</a></li>
<li><a href="/terms">Terms of Service</a></li>
</ul>
</nav>
</footer>
</body>
</html>
<section aria-labelledby="gallery-heading">
<h2 id="gallery-heading">Photo Gallery</h2>

<div class="gallery">
<figure>
<picture>
<source
media="(min-width: 1200px)"
srcset="photo1-large.webp"
type="image/webp"
>
<source
media="(min-width: 768px)"
srcset="photo1-medium.webp"
type="image/webp"
>
<source srcset="photo1-small.webp" type="image/webp">
<img
src="photo1-medium.jpg"
alt="Sunset over mountains with orange and purple sky"
loading="lazy"
>
</picture>
<figcaption>Mountain Sunset</figcaption>
</figure>

<figure>
<picture>
<source
media="(min-width: 1200px)"
srcset="photo2-large.webp"
type="image/webp"
>
<source
media="(min-width: 768px)"
srcset="photo2-medium.webp"
type="image/webp"
>
<source srcset="photo2-small.webp" type="image/webp">
<img
src="photo2-medium.jpg"
alt="Ocean waves crashing on rocky shore"
loading="lazy"
>
</picture>
<figcaption>Ocean Waves</figcaption>
</figure>
</div>
</section>

Advanced Topicsโ€‹

Web Componentsโ€‹

Create reusable custom elements:

<my-card title="Card Title">
<p>Card content here</p>
</my-card>

<script>
class MyCard extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
}

connectedCallback() {
const title = this.getAttribute('title');
this.shadowRoot.innerHTML = `
<style>
:host {
display: block;
border: 1px solid #ddd;
padding: 1rem;
}
h3 { margin-top: 0; }
</style>
<h3>${title}</h3>
<slot></slot>
`;
}
}

customElements.define('my-card', MyCard);
</script>

Content Security Policyโ€‹

Prevent XSS attacks with CSP headers:

<meta http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self' https://trusted.cdn.com">

Microdata and Schema.orgโ€‹

Add structured data for search engines:

<article itemscope itemtype="https://schema.org/BlogPosting">
<h1 itemprop="headline">Article Title</h1>
<p>
By <span itemprop="author">John Doe</span>
on <time itemprop="datePublished" datetime="2024-01-15">Jan 15, 2024</time>
</p>
<div itemprop="articleBody">
<p>Article content...</p>
</div>
</article>

Service Workersโ€‹

Enable offline functionality and caching:

<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(reg => console.log('SW registered', reg))
.catch(err => console.log('SW error', err));
}
</script>

Intersection Observer APIโ€‹

Detect when elements enter viewport:

<img src="placeholder.jpg" data-src="real-image.jpg" class="lazy">

<script>
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
});
});

document.querySelectorAll('.lazy').forEach(img => {
observer.observe(img);
});
</script>

Resource Hintsโ€‹

Optimize resource loading:

<!-- Preconnect to important origins -->
<link rel="preconnect" href="https://fonts.googleapis.com">

<!-- DNS prefetch for multiple domains -->
<link rel="dns-prefetch" href="https://cdn.example.com">

<!-- Preload critical resources -->
<link rel="preload" href="critical.css" as="style">
<link rel="preload" href="hero.jpg" as="image">
<link rel="preload" href="font.woff2" as="font" type="font/woff2" crossorigin>

<!-- Prefetch resources for next navigation -->
<link rel="prefetch" href="next-page.html">

<!-- Module preload for ES modules -->
<link rel="modulepreload" href="module.js">

Summaryโ€‹

This comprehensive guide covers HTML/HTML5 from an interview perspective, including fundamentals, new features, best practices, common questions, and practical coding challenges. Master these concepts to excel in HTML interviews and build better web applications.

Key takeaways:

  • Use semantic HTML for better accessibility and SEO
  • Leverage HTML5 features like new form inputs, multimedia elements, and storage
  • Follow accessibility best practices with ARIA when needed
  • Optimize performance with lazy loading, resource hints, and efficient markup
  • Stay updated with modern web standards and APIs